/*
 * Group:PrePool K9-357 
 * 8/2010
 */
package blo;

import java.util.List;

import util.Constants;
import core.Dictionary;

import dao.ApproveDAO;
import dao.DictionariesDAO;
import dao.ManagerInDictDAO;
import dao.UsersDAO;
import dao.WordDAO;
import dto.DictionaryDTO;
import dto.WordDTO;

/**
 *
 */
public class ApproveBLO {
	private UsersDAO user = new UsersDAO();
	private DictionariesDAO dictDAO = new DictionariesDAO();

	/**
	 * @param word
	 *            WordDTO's instance contains word will be approved
	 * @param username
	 *            the name of the approver
	 * @return true if successful,false if fail
	 */
	public boolean approve(int wordID, String username) {
		WordDTO word = WordDAO.getWord(wordID);
		int dictID = word.getDictID();
		int status = word.getStatus();
		DictionaryDTO dictDTO = dictDAO.getDictionary(dictID);
		ManagerInDictDAO manager = new ManagerInDictDAO();

		// Not a dictionary manager
		if (user.getRole(username) != Constants.ROLE_DICT_MANAGER) {
			return false;
		}

		// If user is a approver
		if (manager.getRole(username, dictID) == Constants.ROLE_APPROVER) {
			if (status == 1) {
				// delete wordID from suggested word list
				WordDAO wordDAO = new WordDAO();
				wordDAO.deleteWord(wordID);
				Dictionary dict = new Dictionary(dictDTO.getM_dicturl(),
						dictDTO.getM_delCount());
				return dict.addWord(word.getWord(), word.getMeaning());
			}
		}

		// If is a reviewer
		else if (manager.getRole(username, dictID) == Constants.ROLE_REVIEWER) {
			if (status == 0) {
				// word is suggested by user
				WordDAO wordDAO = new WordDAO();
				wordDAO.updateWord(wordID, status + 1);
				ApproveDAO.AddApproval(wordID, user.getUserIDByName(username));
				return true;
			}
			else {
				// word is not in suggested stage
			}
		}
		return false;
	}
	
	// get word for approver or reviewer of specified username
	public List<WordDTO> getWordManageByUser(int dictID, String username) {
		ManagerInDictDAO manager =  new ManagerInDictDAO();
		
		// if user is approver
		if(manager.isManager(username, dictID, Constants.ROLE_APPROVER)) 
			return WordDAO.getWords(dictID, 1);
		
		// if user is reviewer
		else if (manager.isManager(username, dictID, Constants.ROLE_REVIEWER)) 
			return WordDAO.getWords(dictID, 0);
		
		else
			return null;
	}
}
